package com.jason.rtsp.server;

import com.jason.rtsp.handler.RtspHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.cors.CorsConfig;
import io.netty.handler.codec.http.cors.CorsConfigBuilder;
import io.netty.handler.codec.http.cors.CorsHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @创建人 zhouhx
 * @创建时间 2023/8/31 16:24
 * @描述 Netty 服务
 */
@Slf4j
@Component
public class NettyVideoServer {

    @Autowired
    private RtspHandler rtspHandler;

    @Value("${netty.port}")
    private Integer port;

    public void start(){
        NioEventLoopGroup masterGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup slaveGroup = new NioEventLoopGroup(200);

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(masterGroup,slaveGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();

                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new HttpRequestEncoder())
                                .addLast(new HttpRequestDecoder())
                                .addLast(new ChunkedWriteHandler())
                                .addLast(new HttpObjectAggregator(64*1024))
                                .addLast(new CorsHandler(corsConfig))
                                .addLast(rtspHandler);
                    }
                })
                .option(ChannelOption.SO_BACKLOG,128)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .option(ChannelOption.ALLOCATOR, PreferHeapByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.TCP_NODELAY,true)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childOption(ChannelOption.SO_RCVBUF,128*1024)
                .childOption(ChannelOption.SO_SNDBUF,1024*1024)
                .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,new WriteBufferWaterMark(1024*1024/2,1024*1024));

        ChannelFuture sync = null;
        try {
            sync = bootstrap.bind(port).sync();
            sync.channel().closeFuture().sync();
            log.info("netty服务启动，端口：{}",port);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            masterGroup.shutdownGracefully();
            slaveGroup.shutdownGracefully();
        }
    }
}
